// pages/login/login.js
Page({
  data: {
    userInfo: null,
    phone: '',
    code: '',
    isSending: false,
    btnText: '获取验证码',
    showEditDialog: false,
    editingUser: {},
    isUploading: false,
    isLoading: false,
    rank: '新兵出征' // 初始化段位
  },

  // 生命周期函数
  onLoad() {
    this.initUserData();
  },

  onShow() {
    this.refreshUserInfo();
  },
  navigateToRank() {
    const points = this.data.userInfo?.points || 0;
    wx.navigateTo({
      url: `/pages/myRank/myRank?points=${points}`
    });
  },

  // 初始化用户数据
  async initUserData() {
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({ userInfo });
      await this.refreshUserInfo(); // 主动刷新确保数据最新
    }
  },

  // 刷新用户信息
  async refreshUserInfo() {
    const user = wx.getStorageSync('userInfo');
    if (!user) return;

    this.setData({ isLoading: true });
    
    try {
      const db = wx.cloud.database();
      const { data } = await db.collection('users').doc(user._id).get();
      
      // 合并并更新用户信息
      const newUserInfo = { 
        ...user, 
        ...data,
        // 保留敏感字段（如openid）
        _openid: user._openid  
      };
      
      wx.setStorageSync('userInfo', newUserInfo);
      this.setData({ 
        userInfo: newUserInfo,
        isLoading: false
      });
      
      // 更新段位
      this.updateRank(newUserInfo.points);

    } catch (err) {
      console.error('用户信息刷新失败:', err);
      this.setData({ isLoading: false });
      wx.showToast({ 
        title: '数据更新失败', 
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 更新段位
  updateRank(points) {
    let rank;
    if (points < 100) {
      rank = '新兵出征';
    } else if (points < 200) {
      rank = '勇士前行';
    } else if (points < 500) {
      rank = '战将无畏';
    } else if (points < 1000) {
      rank = '元帅谋略';
    } else {
      rank = '英雄传奇';
    }
    this.setData({ rank });
  },

  // 登录相关方法
  handlePhoneInput(e) {
    this.setData({ phone: e.detail.value });
  },

  handleCodeInput(e) {
    this.setData({ code: e.detail.value });
  },

  validatePhone(phone) {
    const reg = /^1[3-9]\d{9}$/;
    return reg.test(phone);
  },

  async sendCode() {
    if (this.data.isSending || !this.validatePhone(this.data.phone)) {
      wx.showToast({ title: '手机号格式错误', icon: 'none' });
      return;
    }

    this.setData({ isSending: true });
    let seconds = 60;
    const phone = this.data.phone;
    const genCode = '123456';

    try {
      const db = wx.cloud.database();
      const res = await db.collection('users').where({ phone }).get();
      
      if (res.data.length === 0) {
        // 新用户注册
        await db.collection('users').add({
          data: {
            phone,
            code: genCode,
            username: `用户${phone.slice(-4)}`,
            points: 0,
            rank: "新兵出征",
            avatar: "cloud://cloud1-4g4aia8u2173a4df.636c-cloud1-4g4aia8u2173a4df-1322250303/initAvatar.png",
            createdAt: db.serverDate(),
            updatedAt: db.serverDate()
          }
        });
      } else {
        // 更新现有用户验证码
        await db.collection('users').doc(res.data[0]._id).update({
          data: { 
            code: genCode, 
            updatedAt: db.serverDate() 
          }
        });
      }

      // 倒计时处理
      const timer = setInterval(() => {
        seconds--;
        this.setData({ btnText: `${seconds}秒后重发` });
        if (seconds <= 0) {
          clearInterval(timer);
          this.setData({ 
            isSending: false, 
            btnText: '重新发送' 
          });
        }
      }, 1000);

      wx.showToast({ title: '验证码已发送' });

    } catch (err) {
      console.error('验证码发送失败:', err);
      this.setData({ isSending: false });
      wx.showToast({ 
        title: '发送失败，请重试', 
        icon: 'none' 
      });
    }
  },

  // 登录处理
  async handleLogin() {
    const { phone, code } = this.data;
    if (!phone || !code || code.length !== 6) {
      wx.showToast({ title: '请输入有效信息', icon: 'none' });
      return;
    }

    try {
      const db = wx.cloud.database();
      const res = await db.collection('users')
        .where({ phone, code })
        .get();

      if (res.data.length > 0) {
        const userInfo = res.data[0];
        
        // 更新本地存储和状态
        wx.setStorageSync('userInfo', userInfo);
        this.setData({ 
          userInfo,
          rank: userInfo.rank
        });
        
        wx.showToast({ 
          title: '登录成功',
          icon: 'success',
          duration: 1500
        });
        this.updateRank(userInfo.points);
      } else {
        wx.showToast({ 
          title: '验证码错误', 
          icon: 'none',
          duration: 2000
        });
      }
    } catch (err) {
      console.error('登录失败:', err);
      wx.showToast({ 
        title: '登录服务异常', 
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 用户信息修改相关
  handleEditInfo() {
    this.setData({
      showEditDialog: true,
      editingUser: { ...this.data.userInfo }
    });
  },

  handleUsernameChange(e) {
    this.setData({
      'editingUser.username': e.detail.value
    });
  },

  async uploadAvatar() {
    if (this.data.isUploading) return;
    
    try {
      this.setData({ isUploading: true });
      wx.showLoading({ 
        title: '上传中...', 
        mask: true 
      });

      // 选择并上传图片
      const chooseRes = await wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sizeType: ['compressed']
      });

      if (chooseRes.tempFiles?.[0]?.tempFilePath) {
        const cloudPath = `avatar/${Date.now()}-${Math.random().toString(36).substr(2, 9)}.jpg`;
        const uploadRes = await wx.cloud.uploadFile({
          cloudPath,
          filePath: chooseRes.tempFiles[0].tempFilePath,
        });

        this.setData({
          'editingUser.avatar': uploadRes.fileID
        });
      }
    } catch (err) {
      console.error('头像上传失败:', err);
      wx.showToast({ 
        title: '上传失败', 
        icon: 'none',
        duration: 2000
      });
    } finally {
      this.setData({ isUploading: false });
      wx.hideLoading();
    }
  },

  cancelEdit() {
    this.setData({
      showEditDialog: false,
      editingUser: {}
    });
  },

  async submitEdit() {
    const { editingUser, userInfo } = this.data;
    
    if (!editingUser.username?.trim()) {
      wx.showToast({ 
        title: '用户名不能为空', 
        icon: 'none',
        duration: 2000
      });
      return;
    }

    try {
      const db = wx.cloud.database();
      await db.collection('users')
        .doc(userInfo._id)
        .update({
          data: {
            username: editingUser.username.trim(),
            avatar: editingUser.avatar,
            updatedAt: db.serverDate()
          }
        });

      // 更新本地数据
      const newUserInfo = { 
        ...userInfo, 
        ...editingUser 
      };
      wx.setStorageSync('userInfo', newUserInfo);
      this.setData({ 
        userInfo: newUserInfo,
        showEditDialog: false
      });
      
      // 更新段位
      this.updateRank(newUserInfo.points);

      wx.showToast({ 
        title: '修改成功', 
        icon: 'success',
        duration: 1500
      });

    } catch (err) {
      console.error('信息更新失败:', err);
      wx.showToast({ 
        title: '修改失败', 
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 其他功能
  handleLogout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          this.clearUserData();
          wx.showToast({ 
            title: '已退出登录',
            icon: 'success',
            duration: 1500
          });
        }
      }
    })
  },

  clearUserData() {
    this.setData({ userInfo: null });
    wx.removeStorageSync('userInfo');
  },

  // 工具方法
  generateRandomAvatar() {
    const num = Math.floor(Math.random() * 11) + 1;
    return `cloud://cloud1-4g4aia8u2173a4df.636c-cloud1-4g4aia8u2173a4df-1322250303/touxiang/${num}.png`;
  },

  // 页面跳转
  navigateToShop() {
    wx.navigateTo({ url: '/pages/shop/shop' });
  },

  navigateToPublish() {
    wx.navigateTo({ url: '/pages/publish/publish' });
  },

  navigateToTasks() {
    wx.navigateTo({ url: '/pages/task/task' });
  },
  navigateToPuzzle() {
    const rank = this.data.rank;
    const newUserInfo = { ...this.data.userInfo, rank};
    console.log(newUserInfo);
    const userInfoStr = encodeURIComponent(JSON.stringify(newUserInfo));
    wx.navigateTo({
      url: `/pages/puzzleGame/puzzleGame?userInfo=${userInfoStr}`
    });
  }
});